package other;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Iterator;
import java.util.LinkedList;

import javax.imageio.ImageIO;

import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

public class WebSocketServerTest extends WebSocketServer{
	private JavaCVDemo cvDemo;
	private LinkedList<WebSocket> webSockets=new LinkedList<WebSocket>();
	private byte[] bytes;
	public WebSocketServerTest(JavaCVDemo cvDemo) throws UnknownHostException {
		super();
		this.cvDemo=cvDemo;
	}
	
	public static void main(String[] args) {
		try {
			JavaCVDemo cvDemo=new JavaCVDemo();
			WebSocketServerTest serverTest=new WebSocketServerTest(cvDemo);
			cvDemo.init();
			serverTest.start();
			Thread thread=new Thread(new Runnable() {
				
				@Override
				public void run() {
					while (true) {
						serverTest.sendData();
						try {
							Thread.sleep(40);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			});
			thread.setDaemon(true);
			thread.start();
			cvDemo.loop();
			serverTest.stop();
		} catch (UnknownHostException e1) {
			e1.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onOpen(WebSocket conn, ClientHandshake handshake) {
		webSockets.add(conn);
	}

	@Override
	public void onClose(WebSocket conn, int code, String reason, boolean remote) {
		
	}
	public void sendData(){
		if(webSockets.size()>0){
			Iterator<WebSocket> itr = webSockets.iterator();
			ByteArrayOutputStream output=new ByteArrayOutputStream();
			try {
				ImageIO.write(cvDemo.buffer, "jpg", output);
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			bytes=output.toByteArray();
			
			while (itr.hasNext()) {
				WebSocket webSocket =itr.next();
				if(webSocket.isClosed()||!webSocket.isOpen()){
					itr.remove();
				}else{
					try{
						webSocket.send(bytes);
					}catch(Exception e){
						
					}
					
				}
				
			}
		}
	}

	@Override
	public void onMessage(WebSocket conn, String message) {
		
		
	}

	@Override
	public void onError(WebSocket conn, Exception ex) {
		
	}
	
}
